import { Injectable } from '@nestjs/common';
import { Brand as BrandEntity } from '@/entity/Brand';
import { CommonService } from '../common/common.service';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository, DeepPartial, Like } from 'typeorm';
import { PaginationConfig } from '@/types';
import { InventoryHistory as InventoryHistoryEntity } from '@/entity/InventoryHistory';

@Injectable()
export class BrandService extends CommonService<BrandEntity> {
  constructor(
    @InjectRepository(BrandEntity)
    private readonly brandRepository: Repository<BrandEntity>,
    private dataSource: DataSource,
  ) {
    super(brandRepository);
  }

  async findAllAndCount(
    findOption: DeepPartial<BrandEntity>,
    pagination: PaginationConfig,
  ) {
    const [list, total] = await this.brandRepository.findAndCount({
      where: {
        // 字符串不为空
        name: findOption.name ? Like(`%${findOption.name}%`) : undefined,
        // id 肯定为正整数
        id: findOption.id ? findOption.id : undefined,
      },
      skip: pagination.pageSize * (pagination.current - 1),
      take: pagination.pageSize,
    });
    return {
      list,
      total,
    };
  }

  // 删除品牌及其所有库存记录
  async deleteBrandById(id: BrandEntity['id']) {
    // 开启事务
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    try {
      // 开启事务
      await queryRunner.startTransaction();
      // 删除所有品牌的库存记录
      await queryRunner.manager
        .getRepository(InventoryHistoryEntity)
        .createQueryBuilder()
        .delete()
        .where('brandId = :brandId', { brandId: id })
        .execute();
      // 删除品牌
      await queryRunner.manager
        .getRepository(BrandEntity)
        .createQueryBuilder()
        .delete()
        .where('id = :brandId', { brandId: id })
        .execute();
      // 结束事务
      await queryRunner.commitTransaction();
    } catch (error) {
      // 发生错误回滚
      await queryRunner.rollbackTransaction();
      throw error;
    }
    // 释放
    await queryRunner.release();
  }
}
